/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatserver;

import java.util.ArrayList;

/**
 *
 * @author tiphanie
 */
public class Conversation {

    ArrayList<OnlineUser> users = new ArrayList<OnlineUser>();
    ArrayList<Boolean> participating = new ArrayList<Boolean>();
    int id;

    public Conversation(int id, String[] usernames) {
        this.id = id;
        for (int i = 0; i < usernames.length; i++) {
            users.add(ChatServer.onlineUserForName(usernames[i]));
            participating.add(false);
        }
    }

    void accept(OnlineUser user) {
        int position = users.indexOf(user);
        if (position != -1) { // if user is in the users lis
            participating.set(position, true);
            ChatServer.database.createUserInConversation(user.username, getId());
        }
    }

    void removeUser(OnlineUser user) {
        int position = users.indexOf(user);
        if (position != -1) {
            users.remove(position);
            participating.remove(position);
        }
    }

    void leave(OnlineUser user) {
        int position = users.indexOf(user);
        if (position != -1) {
            participating.set(position, false);
        }
    }

    public void writeLineToParticipants(String line) {
        for (int i = 0; i < users.size(); i++) {
            if (participating.get(i)) {
                users.get(i).connectedClient.writeLine(line);
            }
        }
    }

    public void writeLine(String line) {
        for (int i = 0; i < users.size(); i++) {
            users.get(i).connectedClient.writeLine(line);
        }
    }

    public void writeMessage(OnlineUser user, String message) {
        int position = users.indexOf(user);
        if (position != -1 && participating.get(position)) {
            writeLineToParticipants("message " + getId() + " " + user.username + " " + message);
        }
    }

    String users() {
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < users.size(); i++) {
            out.append(users.get(i).username);
            out.append(" ");
        }
        return out.toString();
    }

    String participants() {
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < users.size(); i++) {
            if (participating.get(i)) {
                out.append(users.get(i).username);
                out.append(" ");
            }
        }
        return out.toString();
    }

    public void sendInvite() {
        writeLine("startConversation " + getId() + " " + users());
    }

    public int getId() {
        return id;
    }
}
